package com.wisdytech.linkdcs.linkdcsservicepad.pad.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wisdytech.app.quality.dao.*;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.linkdcsservicepad.common.CommonConstants;
import com.wisdytech.linkdcs.linkdcsservicepad.common.UtilMapper.CommonMapper;
import com.wisdytech.linkdcs.linkdcsservicepad.common.exception.BaseException;
import com.wisdytech.linkdcs.linkdcsservicepad.common.exception.ServiceException;
import com.wisdytech.linkdcs.linkdcsservicepad.common.handler.BaseService;
import com.wisdytech.linkdcs.linkdcsservicepad.pad.service.IpqcInspectionSheetService;
import com.wisdytech.linkdcs.pad.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2018-08-13
 */
@Service("ipqcInspectionSheetService")
@Transactional
public class IpqcInspectionSheetServiceImpl extends BaseService<IpqcInspectionSheetDao, IpqcInspectionSheet> implements IpqcInspectionSheetService {


    /**
     * 注入设备dao
     */
    @Resource
    private IEqEquipmentDao equipDao;
    /**
     * 注入在制品dao
     */
    @Resource
    private WipDao wipDao;
    /**
     * 注入检验单dao
     */
    @Resource
    private IpqcInspectionSheetDao ipqcInspectionSheetDao;
    /**
     * 注入检验单明细dao
     */
    @Resource
    private IpqcInspectionDetailDao ipqcInspectionDetailDao;
    /**
     * 注入检验记录dao
     */
    @Resource
    private IpqcInspectionRecordDao ipqcInspectionRecordDao;
    /**
     * 注入检验记录dao
     */
    @Resource
    private ProductPqcDao productPqcDao;

    /**
     * 注入检验记录实测值dao
     */
    @Resource
    private IpqcInspectionActualDao ipqcInspectionActualDao;

    @Resource
    private CommonMapper commonMapper;
    @Override
    public Map<String, Object> confirmInspectionTarget(Map<String, String> paramsMap, String inspectionSheetId) {
        Map<String, String> queryMap = this.createQueryMap(paramsMap);
        String username = paramsMap.get("username");
        //判断wip是否存在
        List<Wip> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(queryMap.get("lotNo"))){
            EntityWrapper<Wip> ew = new EntityWrapper();
            ew.eq("LOT_NO",queryMap.get("lotNo"));
            ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
            ew.orderBy("desc");
            list = wipDao.selectList(ew);
            if(list.isEmpty()){
                throw new ServiceException("检验对象不存在");
            }
        }
        //判断该设备正在进行的wip
        if(StringUtils.isNotEmpty(queryMap.get("equipId")) && StringUtils.isNotEmpty(queryMap.get("wipStatus"))){
            EntityWrapper<Wip> ew = new EntityWrapper();
            ew.eq("EQUIP_ID",queryMap.get("equipId"));
            ew.eq("WIP_STATUS",queryMap.get("wipStatus"));
            ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
            list = wipDao.selectList(ew);
            if(list.isEmpty()){
                throw new ServiceException("此设备无正在生产的在制品");
            }
        }

        IpqcInspectionSheet sheet = null;
        if(StringUtils.isNotEmpty(inspectionSheetId)){
            sheet = ipqcInspectionSheetDao.selectById(inspectionSheetId);
            if(!sheet.getInspectionCategory().equals(paramsMap.get("inspectionCategory"))){
                throw new ServiceException("检验类别不一致！");
            }
            EntityWrapper<IpqcInspectionDetail> ew = new EntityWrapper<>();
            ew.eq("INSPECTION_SHEET_ID",inspectionSheetId);
            List<IpqcInspectionDetail> detList = ipqcInspectionDetailDao.selectList(ew);
            Iterator<Wip> it = list.iterator();
            while(it.hasNext()){
                Wip wip = it.next();
                //过滤重复添加的检验对象
                for(IpqcInspectionDetail det:detList){
                    if(wip.getPkId().equals(det.getInspectionTargetId())){
                        it.remove();
                        break;
                    }
                }
                //校验检验对象是否符合要求
                if(!wip.getManufactureId().equals(sheet.getManufactureId()) ||
                        !wip.getOpId().equals(sheet.getOperationId())){
                    throw new ServiceException("同订单同工序同班组的对象才能同时检验！");
                }
                if(StringUtils.isNotBlank(sheet.getGroupId())){
                    if(!sheet.getGroupId().equals(wip.getShiftId())){
                        throw new ServiceException("同订单同工序同班组的对象才能同时检验！");
                    }
                }else if(StringUtils.isNotBlank(wip.getShiftId())){
                    throw new ServiceException("只有同订单同工序同班组的对象才能同时检验！");
                }
            }
            if(list.isEmpty()){
                throw new ServiceException("检验对象已添加！");
            }

        }else {
            //生成检验单
            sheet = this.createIpqcSheet(list.get(0),paramsMap.get("inspectionCategory"),username);
        }

        //保存检验单明细
        if(CommonConstants.INPUT_METHOD_1.equals(paramsMap.get("inputMethod"))){
            IpqcInspectionDetail det = this.createIpqcDetail(list.get(0),sheet.getPkId(),username);
            this.ipqcInspectionDetailDao.insert(det);
        }else{
            for(Wip wip:list){
                IpqcInspectionDetail det = this.createIpqcDetail(wip,sheet.getPkId(),username);
                this.ipqcInspectionDetailDao.insert(det);
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        IpqcInspectionSheet isheet = ipqcInspectionSheetDao.getSheetById(sheet.getPkId());
        map.put("manufactureCode", isheet.getManufactureCode());
        map.put("materialCode", isheet.getMaterialCode());
        map.put("lineName", isheet.getLineName());
        map.put("opName", isheet.getOpName());
        if(StringUtils.isNotBlank(sheet.getGroupId())){
            map.put("shiftName", isheet.getShiftName());
        }
        map.put("inspectionSheetId", sheet.getPkId());

        return map;
    }

    @Override
    public List<IpqcInspectionDetail> getIpqcDetail(String inspectionSheetId) {
        EntityWrapper<IpqcInspectionDetail> ew = new EntityWrapper<>();
        ew.eq("INSPECTION_SHEET_ID",inspectionSheetId);
        List<IpqcInspectionDetail> list = ipqcInspectionDetailDao.selectList(ew);
        return list;
    }

    @Override
    public void checkIpqcDetail(String inspectionDetailId, String username) {
        EntityWrapper<IpqcInspectionRecord> ew = new EntityWrapper();
        List<IpqcInspectionRecord> tempList = this.ipqcInspectionRecordDao.selectList(ew);
        if(tempList.size() > 0){
            return;
        }
        IpqcInspectionDetail det = this.ipqcInspectionDetailDao.selectById(inspectionDetailId);
        IpqcInspectionSheet sheet = this.ipqcInspectionSheetDao.selectById(det.getInspectionSheetId());
        EntityWrapper<ProductPqc> ew1 = new EntityWrapper();
        ew1.eq("PRODUCT_ID",sheet.getProductId());
        ew1.eq("PQC_CATEGORY",sheet.getInspectionCategory());
        List<ProductPqc> list = this.productPqcDao.selectList(ew1);
        if(list.isEmpty()){
            throw new ServiceException("该检验对象未配置检验项！");
        }
        for(ProductPqc pp:list){
            IpqcInspectionRecord rcd = new IpqcInspectionRecord();
            rcd.setInspectionDetailId(inspectionDetailId);
            rcd.setInspectionItemId(pp.getPkId());
            rcd.setItemName(pp.getPqcName());
            rcd.setItemType(pp.getPqcType());
            rcd.setStandValue(pp.getPqcStandardValue());
            if(CommonConstants.ITEM_TYPE_1.equals(pp.getPqcType())){
                rcd.setMinValue(Double.parseDouble(pp.getPqcFloorValue()));
                rcd.setMaxValue(Double.parseDouble(pp.getPqcUpperValue()));
            }
            rcd.setUnit(pp.getPqcUnit());
            rcd.setCreateDate(new Date());
            rcd.setCreateUser(username);
            this.ipqcInspectionRecordDao.insert(rcd);
        }
    }

    @Override
    public List<IpqcInspectionRecord> getIpqcRecord(String inspectionDetailId, String itemType) {
        EntityWrapper<IpqcInspectionRecord> ew = new EntityWrapper<>();
        ew.eq("INSPECTION_DETAIL_ID",inspectionDetailId);
        ew.eq("ITEM_TYPE",itemType);
        ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
        List<IpqcInspectionRecord> list = this.ipqcInspectionRecordDao.selectList(ew);
        return list;
    }

    @Override
    public List<IpqcInspectionActual> getInspectionActual(String inspectionRecordId) {
        EntityWrapper<IpqcInspectionActual> ew = new EntityWrapper();
        ew.eq("INSPECTION_RECORD_ID",inspectionRecordId);
        return this.ipqcInspectionActualDao.selectList(ew);
    }

    @Override
    public void saveInspectionActual(List<IpqcInspectionActual> list, String username) {
        for(IpqcInspectionActual actual : list){
            actual.setCreateDate(new Date());
            actual.setCreateUser(username);
            int count = this.ipqcInspectionActualDao.insert(actual);
            if(count<0){
                throw new ServiceException("新增失败");
            }
        }
    }

    @Override
    public void saveIpqcRecord(List<IpqcInspectionRecord> list) {
        for(IpqcInspectionRecord det:list){
            if(StringUtils.isNotBlank(det.getCreateUser())){
                this.ipqcInspectionRecordDao.updateById(det);
            }else{
                this.ipqcInspectionRecordDao.insert(det);
            }
        }
    }

    @Override
    public void updateIpqcDetail(IpqcInspectionDetail det) {
        det.setInspectionDate(new Date());
        det.setInspectionStatus(CommonConstants.INSPECTION_STATUS_2);
        det.setInspectionUser(det.getCreateUser());
        this.ipqcInspectionDetailDao.updateById(det);
        IpqcInspectionSheet sheet = this.ipqcInspectionSheetDao.selectById(det.getInspectionSheetId());
        if(!CommonConstants.INSPECTION_CATEGORY_4.equals(sheet.getInspectionCategory())){
            Wip wip = this.wipDao.selectById(det.getInspectionTargetId());
            if(CommonConstants.WIP_STATUS_10.equals(wip.getWipStatus())){
                wip.setWipStatus(CommonConstants.WIP_STATUS_15);
            }
            this.wipDao.updateById(wip);
        }
    }

    @Override
    public void deleteInspectionActual(String ids) {
        String[] idArr = ids.split(",");
        List<String> list = new ArrayList<>();
        for (int i = 0;i<idArr.length;i++){
            list.add(idArr[i]);
        }
        this.ipqcInspectionActualDao.deleteBatchIds(list);
    }

    /**
     * 生成检验单明细
     * @param wip
     * @param pkId
     * @return
     */
    private IpqcInspectionDetail createIpqcDetail(Wip wip, String pkId,String username) {
        IpqcInspectionDetail det = new IpqcInspectionDetail();
        det.setInspectionSheetId(pkId);
        det.setInspectionTargetId(wip.getPkId());
        det.setInspectionTargetCode(wip.getLotNo());
        det.setEquipId(wip.getEquipId());
        det.setCreateUser(username);
        det.setCreateDate(new Date());
        det.setInspectionStatus(CommonConstants.INSPECTION_STATUS_1);
        return det;
    }

    /**
     * 生成检验单
     * @param wip
     * @param inspectionCategory
     * @return
     */
    private IpqcInspectionSheet createIpqcSheet(Wip wip, String inspectionCategory,String username) {
        IpqcInspectionSheet sheet = new IpqcInspectionSheet();
        sheet.setSheetNo(commonMapper.createCodeDef("IPQC_NO", null, null, null));
        sheet.setManufactureId(wip.getManufactureId());
        sheet.setProductId(wip.getProductId());
        sheet.setLineId(wip.getLineId());
        sheet.setOperationId(wip.getOpId());
        sheet.setGroupId(wip.getShiftId());
        sheet.setInspectionCategory(inspectionCategory);
        sheet.setInspectionStatus(CommonConstants.INSPECTION_STATUS_1);
        sheet.setUpdateFlag(CommonConstants.BOOL_FLAG_NO);
        sheet.setCreateUser(username);
        sheet.setCreateDate(new Date());
        this.ipqcInspectionSheetDao.insert(sheet);
        return sheet;
    }

    private Map<String, String> createQueryMap(Map<String, String> paramsMap) {
        Map<String, String> queryMap = new HashMap<String, String>();
        //1:检验对象
        if(CommonConstants.INPUT_METHOD_1.equals(paramsMap.get("inputMethod"))){
            queryMap.put("lotNo", paramsMap.get("inspectionTargetCode"));
        }else{
            String equipCode =  paramsMap.get("inspectionTargetCode");
            EntityWrapper<Equipment> ew = new EntityWrapper();
            ew.eq("EQUIP_CODE",equipCode);
            List<Equipment> equipList = equipDao.selectList(ew);
            if(equipList.isEmpty()){
                throw new ServiceException("设备不存在！");
            }
            queryMap.put("equipId", equipList.get(0).getPkId());
            queryMap.put("wipStatus", CommonConstants.WipStatus.STATUS_10);
        }
        return queryMap;
    }
}
